<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class UserModel extends Model
{
    protected $table = 'user';

    //插入用户 注册
    public function insertUser($username , $password) {
        //随机生成盐
        $salt = \Str::random(6);
        //MD5加密
        $password = md5($password.$salt);
        //插入
        $this->username = $username;
        $this->password = $password;
        $this->salt = $salt;
        $res = $this->save();

        return $res;
    }

    //检验用户名是否存在
    public function checkName($username) {
        $user = self::where('username' , $username)->first();
        if ($user) {
            return [ 'status' => 'fail'];
        } else {
            return [ 'status' => 'success'];
        }
    }

    //用户登录
    public function checkUser($username , $password) {
        $user = self::where('username' , $username)->first();

        //判断用户名是否正确
        if ( !$user ) {
            return ['msg' => '用户名不存在' , 'status' => 'fail'];
        }

        //判断该用户是否冻结
        if ( !$user->is_freeze ) {
            return ['msg' => '该用户已被冻结' , 'status' => 'fail'];
        }
        
        $user = $user->toArray();
        $pass = md5($password.$user['salt']);

        //判断密码是否正确
        if ( $pass != $user['password'] ) {
            return ['msg' => '密码错误' , 'status' => 'fail'];
        }
        
        session(['user' => $username]);

        return ['msg' => '登录成功' , 'status' => 'success'];
    } 

    //获取用户
    public function getUsers() {
        $res = self::select('id' , 'username' , 'created_at' , 'is_freeze')
                    ->orderBy('id' , 'desc')
                    ->paginate(5);
        return $res;
    }

    //冻结用户
    public function freezeUser($id) {
        $freeze = self::where('id' , $id)->value('is_freeze');

        $freeze = intval(!$freeze);

        $res = self::where('id' , $id)->update(['is_freeze' => $freeze]);

        return $res;
    }
}
